package com.tasty.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.tasty.constant.MessageConstant;
import com.tasty.constant.StatusConstant;
import com.tasty.dto.DishDTO;
import com.tasty.dto.DishPageQueryDTO;
import com.tasty.entity.Dish;
import com.tasty.entity.DishFlavor;
import com.tasty.entity.Setmeal;
import com.tasty.entity.SetmealDish;
import com.tasty.exception.DeletionNotAllowedException;
import com.tasty.mapper.DishFlavorMapper;
import com.tasty.mapper.DishMapper;
import com.tasty.mapper.SetmealDishMapper;
import com.tasty.mapper.SetmealMapper;
import com.tasty.result.PageResult;
import com.tasty.service.DishService;
import com.tasty.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


@Service
@Slf4j
public class DishServiceImpl implements DishService{

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorServiceImpl dishFlavorService;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 新增菜品和相关口味
     * @param dishDTO
     */

    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {

        Dish dish = new Dish();

        BeanUtils.copyProperties(dishDTO,dish);

        //向菜品表插入一条数据
        dishMapper.insert(dish);

        //获取菜品表Id
        Long dishId = dish.getId();




        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0){

            //遍历flavors每一条数据，把Id传进去
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });
            //向口味表插入n条数据
            dishFlavorService.saveBatch(flavors);

        }

    }

    /**
     * 菜品分页查询
     * @param dishPageQueryDTO
     * @return
     */

    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {

        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());

        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);

        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 菜品批量删除
     * @param ids
     */

    @Transactional
    public void deleteBatch(List<Long> ids) {

        for (Long id : ids ) {

            Dish dish = dishMapper.selectById(id);

            if (dish.getStatus() == StatusConstant.ENABLE){
                //当前菜品起售中，不能删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }


        QueryWrapper<SetmealDish> dishId = new QueryWrapper<SetmealDish>().select("dish_id");
        List<SetmealDish> setmealIds = setmealDishMapper.selectList(dishId);
            if (setmealIds != null && setmealIds.size() > 0 ){
                //判断当前菜品是否与套餐关联
                throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_DISH);
            }

        //根据主键删除菜品表数据
        for (Long id : ids) {
            dishMapper.deleteById(id);
            //删除菜品表对应的口味表数据

            dishFlavorMapper.deleteByDishId(id);
        }

    }

    /**
     * 根据菜品id查询菜品数据
     * @param id
     * @return
     */


    public DishVO getByIdWithFlavor(Long id) {

        //根据id查询菜品数据
        Dish dish = dishMapper.selectById(id);

        //根据dishid查询口味数据
        List<DishFlavor> dishFlavors = dishFlavorMapper.selectByDishId(id);

        //将查询到的数据封装到DishVO对象中
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(dishFlavors);

        return dishVO;

    }

    /**
     * 修改菜品信息
     * @param dishDTO
     */

    public void updateWithFlavor(DishDTO dishDTO) {

        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);

        //修改菜品基本信息
        dishMapper.updateById(dish);

        //删除原有口味数据
        dishFlavorMapper.deleteByDishId(dishDTO.getId());

        //重新插入口味数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0){

            //遍历flavors每一条数据，把Id传进去
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishDTO.getId());
            });
            //向口味表插入n条数据
            dishFlavorService.saveBatch(flavors);

        }
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {


        QueryWrapper<Dish> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_id",dish.getCategoryId());
        queryWrapper.eq("status",dish.getStatus());
        List<Dish> dishList = dishMapper.selectList(queryWrapper);
        //List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            //List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());
            List<DishFlavor> dishFlavors = dishFlavorMapper.selectByDishId(d.getId());

            dishVO.setFlavors(dishFlavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

    /**
     * 菜品起售停售
     *
     * @param status
     * @param id
     */
    @Transactional
    public void startOrStop(Integer status, Long id) {

        Dish dish = new Dish();
        dish.setStatus(status);
        QueryWrapper<Dish> updateWrapper = new QueryWrapper<Dish>().eq("id",id);

        dishMapper.update(dish,updateWrapper);

        if (status == StatusConstant.DISABLE) {
            // 如果是停售操作，还需要将包含当前菜品的套餐也停售
            List<Long> dishIds = new ArrayList<>();
            dishIds.add(id);
            // select setmeal_id from setmeal_dish where dish_id in (?,?,?)
            //List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(dishIds);


            QueryWrapper<SetmealDish> wrapper = new QueryWrapper<SetmealDish>()
                    .select("setmeal_id")
                    .in("dish_id",dishIds);

            List<SetmealDish> setmealIds = setmealDishMapper.selectList(wrapper);

            if (setmealIds != null && setmealIds.size() > 0) {
                for (int i = 0; i < setmealIds.size(); i++) {
                    Setmeal setmeal = Setmeal.builder()
                            .id(setmealIds.get(i).getSetmealId())
                            .status(StatusConstant.DISABLE)
                            .build();
                    setmealMapper.update(setmeal);
                }
            }

        }
    }
}
